'Linux - How to get a string specific string from a specific line?
Lets say that I have the following DeletedFiles.txt
file:
test1.zip - date-removed='6-16-2021'
test2.zip - date-removed='6-17-2021'
test3.zip - date-removed='6-17-2021'
test4.zip - date-removed='6-17-2021'
I want to for example only grab the date from test3.zip
.
I have the number of the line that test3.zip
is on.
How can I make it so that when I run the following code it only returns the date from the specific file I want it from, in this case from the file test3.zip
so that the output will be 6-17-2021
I have the following code:
Line=$(GetLine $File)
LineNumber=`echo $Line | cut -c1-1`
DateRemoved=$(sed -e "s/.*'\(.*\)'/\1/" DeletedFiles.txt)
echo "$DateRemoved"
But when I run this it returns the dates from ALL the files:
6-16-2021
6-17-2021
6-17-2021
6-17-2021
And when I try the following code:
Line=$(GetLine $File)
LineNumber=`echo $Line | cut -c1-1`
DateRemoved=$(sed -e "/$LineNumber/s/.*'\(.*\)'/\1/" DeletedFiles.txt)
echo "$DateRemoved"
It returns everything from ALL lines:
test1.zip - date-removed='6-16-2021'
test2.zip - date-removed='6-17-2021'
test3.zip - date-removed='6-17-2021'
test4.zip - date-removed='6-17-2021'
How can I fix this so that it only returns the date from the file I want?
Solution 1:[1]
With a simple command you can solve it. grep test3\.zip DeletedFiles.txt
Solution 2:[2]
I'd use awk for this:
$ awk -F"[ ']" -v file="test3.zip" '$1 == file {print $(NF-1)}' DeletedFiles.txt
6-17-2021
Solution 3:[3]
With sed
sed -n "/^test3\.zip /s/.*date-removed='\([^']*\).*/\1/p" file.txt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | glenn jackman |
Solution 3 | Jetchisel |