如何一一改变字符串的字符?

如何一一改变字符串的字符?

我想根据替换规则将字符串中的所有字符一一更改并保存到Linux上的文件中。

这是替换文件(sub.txt)。

A -> Y
B -> V
C -> Q
...

输入文件:

ABCDEFGHIJ

首先,(A到Y)YBCDEFGHIJ->保存文件

第二,(B到V)AVCDEFGHIJ->保存文件

我应该采用哪种方法?

答案1

给出sub.txt这样的:

$ cat sub.txt 
A -> Y
B -> V
C -> Q
D -> K
E -> L
F -> O
G -> P
H -> W
I -> X
J -> Z

您可以在 shell 循环中对其进行迭代,将每行上的三个元素读取到一个变量中:

while IFS=' ' read -r from ignore to; do ... ; done < sub.txt

在该while循环中,$from是源字符, 是$to您想要替换的字符。中间$ignore的只是一个支架->

这假设空格和换行符(' '\n)不在您要音译的字符列表中。

考虑到这一点,您可以使用tr进行更改并将输出重定向到新文件:

while IFS=' ' read -r from discard to; do 
    printf '%s\n' "$string" | tr "$from" "$to" > changed."$from".txt
done < sub.txt 

请注意,如果或是多字节字符,某些tr实现将会失败。上面还假设不是。$from$to[$from/

如果string="ABCDEFGHIJ",上面的命令将创建这些文件:

$ ls changed*
changed.A.txt  changed.D.txt  changed.G.txt  changed.J.txt
changed.B.txt  changed.E.txt  changed.H.txt
changed.C.txt  changed.F.txt  changed.I.txt

包含以下内容:

$ for f in changed.*; do printf '%s\n' "=== $f ==="; cat "$f"; done
=== changed.A.txt ===
YBCDEFGHIJ
=== changed.B.txt ===
AVCDEFGHIJ
=== changed.C.txt ===
ABQDEFGHIJ
=== changed.D.txt ===
ABCKEFGHIJ
=== changed.E.txt ===
ABCDLFGHIJ
=== changed.F.txt ===
ABCDEOGHIJ
=== changed.G.txt ===
ABCDEFPHIJ
=== changed.H.txt ===
ABCDEFGWIJ
=== changed.I.txt ===
ABCDEFGHXJ
=== changed.J.txt ===
ABCDEFGHIZ

这分别改变了每个角色。如果您想逐步执行此操作,因此第一个文件将仅更改第一个字符,但第二个文件将更改第一个和第二个字符,您可以执行以下操作:

tmpFile=$(mktemp) 
printf '%s\n' "$string" > "$tmpFile" 
while IFS=' ' read -r from ignore to; do 
    tr "$from" "$to" < "$tmpFile" > changed."$from".txt
    cp changed."$from".txt "$tmpFile"
done < sub.txt 

这将创建以下文件:

$ for f in changed.*; do printf '%s\n' "=== $f ==="; cat "$f"; done
=== changed.A.txt ===
YBCDEFGHIJ
=== changed.B.txt ===
YVCDEFGHIJ
=== changed.C.txt ===
YVQDEFGHIJ
=== changed.D.txt ===
YVQKEFGHIJ
=== changed.E.txt ===
YVQKLFGHIJ
=== changed.F.txt ===
YVQKLOGHIJ
=== changed.G.txt ===
YVQKLOPHIJ
=== changed.H.txt ===
YVQKLOPWIJ
=== changed.I.txt ===
YVQKLOPWXJ
=== changed.J.txt ===
YVQKLOPWXZ

答案2

使用 sed :

要一一更改字符串中的两个字符,

sed -i 's/A/Y/;s/B/V/' file 

要更改并保存在不同的文件中:

sed 's/A/Y/' file > file1; sed 's/B/V/' file > file1

答案3

通过下面的方法完成并且效果很好

    awk '{gsub("A","Y",$0);print $0}' l.txt > f_1.txt
    awk '{gsub("B","V",$0);print $0}' l.txt > f_2.txt
    awk '{gsub("C","Q",$0);print $0}' l.txt > f_3.txt

答案4

我根据用户输入制作了脚本,这样就可以避免错误

    #!/bin/bash
    echo "enter the character need to display"
    read old
    echo "enter the  need character to be replaced"
    read new
    sed "s/$old/$new/g" r.txt>file_$old.txt



First it will ask for old content which need to be replaced. 
Second it will ask for new content which needs to be replaced with old content
THird it saves the file  after each iteration

Based on how  characters need to be replaced you can add above mentioned script in for loop

相关内容