Reputation: 664
I am trying to trim the data above the line from a file, where line containing some string by passing variable to it
varfile=$(cat variable.txt)
echo "$varfile"
if [ -z "$varfile" ]; then
echo "null"
else
echo "data"
sed "1,/$varfile/d" fileee.txt
fi
Here I am taking a string from variable.txt file and trying to find that text in fileee.txt file and removing all the data above the line
EX: variable.txt has 3 I am finding 3 in fileee.txt and removing data above three
INPUT:
1
2
3
4
OUTPUT:
3
4
Upvotes: 0
Views: 35
Reputation: 6527
I suppose the issue here is that you want to remove all lines before the match, but not the matching line itself?
One way, with GNU sed, is to explicitly add a print for the matching line first:
pattrn=3
seq 1 4 | sed -e "/$pattrn/p;1,/$pattrn/d"
Though this will duplicate any further lines that match the pattern.
Better, invert the sense of the match:
seq 1 4 | sed -ne "/$pattrn/,\$p"
That is, don't print by default (-n
), but print (p
) anything from a match to the end ($
, escaped because of the double-quoted string)
Even better would be to use awk
:
pattrn=3
seq 1 4 | awk -vpat="$pattrn" '$0 ~ pat {p=1} p'
This sets a flag on the line where the whole line ($0
) matches the pattern (~
is a regex match), then prints the lines whenever that flag is set.
The awk
solution is also better in that special characters in the pattern don't cause issues (at least not as many); in the sed
case, if the pattern contains a slash /
, it will terminate the regex in the sed
code, and cause syntax errors or allow for code injection.
I used seq
from GNU coreutils here only to make up the sequence of numbers for input.
Upvotes: 2