I want to cut the characters n-N of a line, but ONLY if the line begins with certain characters, otherwise I want to print the whole line.
Simplified File example:
John
123456987123
Mark
123546792019
I want to make two new files, one with the FIRST 6 numbers and the other with the last 6 numbers, but still containing the headers, so
John
123456
Mark
123546
John
987123
Mark
792019
Can I tell grep cut to only cut if the string matches, but to otherwise give the whole file? What sort of awk command can cut lines if a condition is met or otherwise print the whole line?
Tha开发者_Go百科nks
Grep can only grep, not cut.
awk '/^[0-9]/{print(substr($0,0,6));next;}
# Fall through here in case of no match
{print}' inputfile
You can generate your 2 files in a single sed script, reading your input file only once. Put what is bellow in a text file, and run is with sed -f script_file input_file
. It will generate the f1 and f2 files and output the input file.
/^[^0-9]/{
w f1
w f2
}
/^[0-9]/{
h
s/^\(.\{6\}\).*/\1/
w f1
g
s/^.\{6\}//
w f2
g}
grep should be fine:
grep -E -o '^[0-9]{6}|^[^0-9].*' input > first.txt
grep -E -o '[0-9]{6}$|^[^0-9].*' input > last.txt
精彩评论