Reputation: 1
I am trying to change in the first column of an input text two characters and doing that for multiple files -250 in this case-, using awk
but I get errors. My level is beginner, so I started without including the multiple files, starting just for a single one.
Input text: *.xyz
6 -2.163968 -0.214364 0.000000
1 -1.578434 -2.353198 0.000000
1 1.575214 2.351350 0.000000
6 -4.697660 0.932898 0.000000
1 -3.168017 3.994185 0.000000
1 -5.599375 2.978998 0.000000
so the text will have different characters like 6 or 1 or more in the first column only and I want to replace only those with C for 6 and H for 1. What I try changes all of the numbers 6 and 1 or just prints error.
awk -F, -vOFS=, '{for(n=1;n<=1;n++)sub(/\6/,"C",$1)}1' *.xyz
awk ' NF >= 4 { $(NF - 3) = "sub(/\C,"6",$1)"; print; }' *.xyz
which does not work.
What do I need to change?
Upvotes: 0
Views: 156
Reputation: 10039
awk '{ if( $1 == 6 ) $1 = "C"; else $1 = "H"; print}' *.xyz
if space separator are important
awk '{ sub( /^6/, "C");sub( /^1/, "H"); print}' *.xyz
Upvotes: 0
Reputation: 3833
plan
- use sed to in-place replace these fields
note 1.xyz and 2.xyz contain identical contents as posted in question
replace_first.sh
#!/bin/bash
for i in ./*.xyz;
do
printf "processing $i\n";
sed -i -e 's/^1\(\s\)/H\1/g' \
-e 's/^6\(\s\)/C\1/g' "$i";
done;
output
$ ./replace_first.sh
processing ./1.xyz
processing ./2.xyz
$ cat 1.xyz
C -2.163968 -0.214364 0.000000
H -1.578434 -2.353198 0.000000
H 1.575214 2.351350 0.000000
C -4.697660 0.932898 0.000000
H -3.168017 3.994185 0.000000
H -5.599375 2.978998 0.000000
$ cat 2.xyz
C -2.163968 -0.214364 0.000000
H -1.578434 -2.353198 0.000000
H 1.575214 2.351350 0.000000
C -4.697660 0.932898 0.000000
H -3.168017 3.994185 0.000000
H -5.599375 2.978998 0.000000
Upvotes: 2