Hi. im trying to retrieve the line number from grep. i have 1 part of my code here.
grep -n $tgt file.txt | cut -f 1 -d ":"
when i do not cut the value i have is 12:aaa:abc:aaa:aaa:aaa
how can i store the value of 12 or my whole line of string into a variable with grep?
varname=$( grep -n "$tgt" file.txt | cut -f 1 -d ":" )
1 Like
posix
3
Storing values in an array is bad idea , better to do some operation with that
for var in ` grep -n pattern file_name | cut -f 1 -d ":" `; do
echo "it has line number:$var" #do your operations
done
1 Like
thank you very much. i have 1 more question.
i am actually trying to update the file with matching pattern. the pattern will be unique so there will always be 1 pattern.
$ sed $var`s`/$oldpattern/$newpattern file.txt
i tried using the () but i still get errors. is it because the code after my sed is not a command due to the `s`?
For in-file editing (be wary while doing this):
sed -i 's/pattern/replacement/' file.txt
1 Like
You probably mean
sed "$var s/$oldpattern/$newpattern/" file.txt
where var is the loop variable with the line number?
Why not replace the whole thing with one sed
sed '
s/pattern1/newpattern1/
s/pattern2/newpattern2/
' file.txt
Or
sed '
/addrpattern1/ s/pattern1/newpattern1/
/addrpattern2/ s/pattern2/newpattern2/
' file.txt
Once the output looks okay, you can overwrite file.txt with the -i option (only available in GNU sed).
1 Like
Thanks alot. i got what i needed.