How to add string at specific column in a file which is not a white space.

cat file.txt


Now I want to add string "test? at column # 8 of file.txt. But column #8 is not a white space then how can I add string?

It should be -

abc    test
defg   test
xy     test




It looks like you want to print the first field left-justified within a fieldwidth of 8:

$ awk -v s=test '{printf "%-8s%s\n", $1, s}' file.txt
abc     test
defg    test
xy      test
  • Not working. Please note that there is no whitespace after end of line.(eg- after word "abc" there is no any white space ) – Vishal Patel Dec 5 '18 at 6:43
  • 1
    @VishalPatel the solution does not require there to be any whitespace at the end of the line (aside from the newline character, obviously) – steeldriver Dec 5 '18 at 13:22
  • The beauty of this solution is that it doesn't rely on column 8 being just one tab away and it is easily adjustable to column 9, for instance. – PerlDuck Dec 5 '18 at 15:47

Pretty quick and dirty solution using paste, yes, and head:

paste file.txt <(yes test | head -n 3)
  • yes prints endless lines of test
  • head gets just the first three lines from yes
  • <(...) redirects the output of ... into paste as an input file
  • paste joins the two input files together

Using the sed command should help with this:

sed -E 's/([[:alpha:]]*)/\1 \ttest/g' data.txt

Either run:

  1. And created a backup:

    sed -i.bak -E 's/([[:alpha:]]*)/\1 \ttest/g' data.txt
  2. Redirect into another file:

    sed -E 's/([[:alpha:]]*)/\1 \ttest/g' data.txt > result.txt


abc     test
defg    test
xy      test


  • ([[:alpha:]]): capture alphabets
  • \1 \ttest: return the captured group and add a tab and the word test
  • -E: Extended regex option for portability.

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.