I want to delete all the words before a pattern for example: I want to delete all the words before STAC
.
Input:
asd
asdd
asddd
STAC
asd
as
Output:
STAC
asd
as
I have this code sed -ni "s/^.*STAC//d" myfile
sed
works linewise, that's why your try will not work.
So how to do it with sed
? Define an address range, starting from the STAC
line (/^STAC$/
) to the end of the file ($
). Those should be printed, so everything else (!
) should get d
eleted:
sed -i '/^STAC$/,$!d' myfile
-i
option requires an argument (extension) for BSD sed
and is not part of the standard. While the OP obviously uses GNU sed
, your remark is valuable for future readers, so thank you!
Commented
Aug 9, 2019 at 17:16
An awk
variant which prints all lines after the match (including the match):
$ awk '/^STAC$/ { out=1 } out' file
STAC
asd
as
This matches the line that only contains the string STAC
and sets out
to a non-zero value. For each line, if out
is non-zero, print it.
Use $0 == "STAC"
instead of /^STAC$/
to do a string comparison instead of a regular expression match.
Slightly more obfuscated but shorter, using the boolean result of the match with the regular expression as an integer (will be 0 for a non-match, and 1 for a match):
awk 'p += /^STAC$/' file
If the result in p
is non-zero, which it will be from the point where the regular expression first matches, the current line will be printed.
Use p += ($0 == "STAC")
instead of p += /^STAC$/
to do a string comparison instead of a regular expression match.
Another option would be to use a scriptable editor like ed
:
printf '%s\n' '1,/^STAC/-1 d' 'wq' | ed -s myfile
This prints two commands to ed
:
STAC
)The -s
option inhibits ed
's default printing of the number of bytes read & written.
Using awk
:
awk '/^STAC$/,/$ /' input
This will print all lines between STAC
and anything (including the matching lines)
Or using a grep
that supports the -z
option (BSD grep does not):
Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline.
grep -z 'STAC' input
grep -wn STAC file.txt | cut -d":" -f 1 | xargs -I % sed '1,%d' file.txt
Get line number of the word, pass it to xargs and use sed to delete.
awk '/^STAC$/,0'
,awk '$0=="STAC",0'
,grep -A100000 '^STAC$'