jueves, 5 de febrero de 2015

awk / cut: Skip First Two Fields and Print the Rest of Line


by on July 13, 2011 · 7 comments· LAST UPDATED July 13, 2011
I'd like to skip first two or three fields at the the beginning of a line and print the rest of line. Consider the following input:
This is a test
Giving back more than we take
I want my input file with the following output:
a test
more than we take
How do I printing lines from the nth field using awk under UNIX or Linux operating systems?

You can use the awk command as follows:
 
echo 'This is a test' | awk '{print substr($0, index($0,$3))}'
 
OR
 
awk '{print substr($0, index($0,$3))}' <<< 'This is a test'
 
You can also use the cut command:
 
echo 'This is a test' | cut -d ' ' -f3-
 
OR
 
cut -d ' ' -f3- <<<'This is a test'
 
Finally, process the file using bash while loop:
#!/bin/bash
_input="/path/to/file.name.txt"
while IFS= read -r line
do
    cut -d ' ' -f3- <<<"$line"
    ### same stuff with awk ###
    ### awk '{print substr($0, index($0,$3))}' <<< "$line" ###
done < "${_input}"
 

No hay comentarios:

Publicar un comentario