I have data in text in a 4 columns but the last column is a text (contains variable strings) like as shown below

Column1 Column2 Column3 Column4
5678    567     56      hello
1234    123     12      hello there

I want to write or display only the 4th column using awk like: awk '{print $4}' but column4 only shows the first string. How can I be able to show text using awk or any other formatting command.



I think the easiest way is probably a mix of tr (to ensure there's only one space between each column) and cut to grab the 4th and subsequent columns:

$ cat test.txt | tr -s ' ' | cut -f 4- -d ' '
hello there

If you're certain that all the columns are alligned, with spaces (not tabs), then this is shorter:

$ cut -c 25- < test.txt
hello there

And the obligatory awk solution:

$ awk '{ $1=$2=$3=""; print $0 }' < test.txt
   hello there

Note the whitespace at the start of each line of output, compared to the previous two solutions.


Column 4 is getting split when you use {print $4} because awk interprets and space (for example between "hello" and "there") as a delimiter, and in this example the "there" would be in field 5.

Depending on exactly how your file is formatted, there are a number of possible answers (some easier than others).

If all of the columns are separated by a single tab character, use

awk -F \t '{print $4}' (-F here sets the filed separator to a single tab)

If all of the columns are separator by one or more tab characters, use

awk -F '[\t]+' '{print $4}' (-F here sets the field separator to one or more tabs)

If the first there columns are always a fixed number of characters (say 20) then use

awk '{print substr($0, 21)}'

(the substr command simply prints the input lime from the 21st character to the end)

or, if none of the above

awk '{for (i=4; i<=NF; i++) printf "%s ", $i print ""}'

(this loop prints all fields from the fourth to the end of the line)


If the format of your input file is that each column is separated by two or more spaces, and a valid entry in column 4 will never have more than one space in a row, you could use the following solution, where the field separator is set to two or more spaces.

awk -F " [ ]+" '{print $4}'

Sample output:

hello hello there

(Note that the header "Column4" was rejected because there is only one space between each of the headings)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.