开发者

Replace space character at the end of a line with a specific string

开发者 https://www.devze.com 2023-03-26 08:28 出处:网络
I\'m dealing with space delimited file with 6 fields: Pop1 ID60776 62 C 10 62 Pop1 ID62442 13 A 2 13 Pop1 ID63614 56 C 0

I'm dealing with space delimited file with 6 fields:

Pop1 ID60776 62 C 10 62
Pop1 ID62442 13 A 2 13
Pop1 ID63614 56 C 0 
Pop1 ID67511 61 T 37 61
Pop1 ID68222 51 A 0 
Pop1 ID68407 65 C 16 65

However, in lines 3 and 5, there are only 5 fields. In these cases, the 0 in field 5 is followed by a space character ('0 ').

I would l开发者_运维知识库ike to find all instances of a space character at the end of a line (i.e. \s$ ) and replace it with space NA (i.e. '\sNA') but I am having real trouble doing so. For example, I have tried sed:

sed s/\\s$/\\sNA/g

but it's not working. Can someone help me out?

Thank you!


Here's a couple of equivalent solutions in awk:

awk '{ printf("%s", $0) } NF == 5 { printf("NA") } { printf("\n") }

and

awk '{ print $0 (NF==5 ? "NA" : "") }'


  1. \s can't be used in the replacement string since it is a class.
  2. The $ is probably being interpreted by the shell.

Try:

sed -e's/\s$/ NA/' 


Put a real space instead of \s, and use single quote (') to avoid the shell to perform variable substitution:

sed -e 's/ $/ NA/'


You can do that in pure bash shell, avoiding to start a sed or awk process:

while read line; do
  printf "%s" "$line"
  nbchar=${#line}
  if [ ${line:$((nbchar-1))} == " " ] ; then printf "NA"; fi
  printf "\n"
done < your_file
0

精彩评论

暂无评论...
验证码 换一张
取 消