Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

awk - Need to replace all the strings staring with 0 (except having / and .) in a text file with same string in double quotes

    awk '{for(i=1;i<=NF;i++){if($i~/^0[a-z,0-9][a-z,0-9]/){print $i}}}' test1 > test3

 doWork()

 { rm /tmp/test1 && awk '{sub(/'$I'/, ""'$I'"", $0); print}' >test1;} < test1

 for I in `cat /tmp/test3`
 do doWork;
 done;

Input text file:

/tmp # cat test1 1234 012345 0.000 01/02/03 01234 05554567 0qwertyu 0099 0000 000012 1800.000000 099000 0123456789

Current Output:

1234 ""01234"5" 0.000 01/02/03 "01234" "05554567" "0qwertyu" "0099" "0000" "000012" 1800."0000"00 "099000" ""01234"5"6789

Expected output:

1234 "012345" 0.000 01/02/03 "01234" "05554567" "0qwertyu" 0099 "0000" "000012" 1800.000000 "099000" "0123456789"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes 0099 also should be quoted. I forgot by mistake.

$ awk -v q='"' '{for(i=1; i<=NF; i++)if($i ~/^0[[:alnum:]][^./]/)$i=q $i q}1' infile
1234 "012345"
0.000
01/02/03
"01234"
"05554567"
"0qwertyu"
"0099"
"0000" "000012"
1800.000000
"099000"
"0123456789"

Input:

$ cat infile
1234      012345
0.000
01/02/03
01234
05554567
0qwertyu
0099
0000           000012
1800.000000
099000
0123456789

Explanation:

/^0[[:alnum:]][^./]/

  • ^ asserts position at start of the string
  • 0 matches the character 0 literally
  • Match a single character present in the list below [[:alnum:]] [:alnum:] matches a alphanumeric character [a-zA-Z0-9]
  • Match a single character not present in the list below [^./] . matches the character . literally / matches the character / literally

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...