0

This is the abc.txt file which consist of 5 columns:

ID|first name|middle name|last name|address 
1 | john     | whatever  | smith   | somewhere

How do I get this output:

ID|first name middle name last name|address
1 | john whatever smith            |somewhere

How do I replace the '|' with space only on specific columns to a new file def.txt. In this case, 2nd column until 4th column.

1

awk solution:

awk 'BEGIN{ FS=OFS="|" }{ cs=$2$3$4; gsub(/ +/, " ", cs); print $1,sprintf("%-32s",cs),$5 }' abc.txt
  • FS=OFS="|" - field separator

  • cs=$2$3$4 - concatenated 2nd, 3rd and 4th field

  • gsub(/ +/, " ", cs) - removing redundant spaces

  • sprintf("%32s",cs) - formatted concatenated string


The output:

ID|first namemiddle namelast name  |address 
1 | john whatever smith            | somewhere
  • It does not have space in between them – user6308605 Aug 10 '17 at 8:05
  • @user6308605, see my update – RomanPerekhrest Aug 10 '17 at 8:11
  • Still no space in between them (the combine columns) – user6308605 Aug 10 '17 at 8:18
  • I noticed, using your cmd, it will remove the rest of word containing special character like 'Arrehøj' to 'Arreh' – user6308605 Aug 10 '17 at 8:21
  • 2
    @user6308605, what are you talking about? Your input doesn't have special characters. Post screenshots or extend your input to avoid confusing – RomanPerekhrest Aug 10 '17 at 8:31
0

Using sed:

sed -e 's,|\([^|]*\)|\([^|]*\)|,|\1 \2 ,' abc.txt > def.txt

Here is a nice introduction that covers the used s features.

  • if I have more columns to combine, I need to add |\([^|]*\) according to how many columns i want to combine? – user6308605 Aug 10 '17 at 8:08
  • Yes, also you need to add \3 \4 and so on to the right part of the s command so the field contents won't get removed altogether with | symbols. – L29Ah Aug 10 '17 at 8:11
  • sed -e 's,|\([^|]*\)|\([^|]*\)|\([^|]*\)|\([^|]*\)|\([^|]*\)|,|\1 \2 \3 \4 \5 ,' abc.txt > def.txt does not working. I try to combine 2nd column to 6th column now – user6308605 Aug 10 '17 at 8:24

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.