有人可以帮我写一个脚本来翻译每行中的第三个单词,单词用制表符分隔。
样本输入:
Hello how Are You
Iam Fine how about
样本输出:
Hello how Ziv You
Iam Fine sld about
每行中的第三个单词应按如下方式翻译:tr '[abcdefghijklmnopqrstuvqxyz]' '[zyxwvutsrqponmlkjihgfedcba]'
鉴于以下情况:
[somedude@dev7 ~]# cat so.txt
Hello how Are You
Iam Fine how about
[somedude@dev7 ~]#
我会跑:
[somedude@dev7 ~]# cat so.sh
#!/bin/bash
_INPUT="Hello how Are You
Iam Fine how about"
# read each line from config file
while read -r l
do
_GET_THIRD_WORD=$(echo $l | awk '{print $3}')
echo $_GET_THIRD_WORD | sed -i "s,$_GET_THIRD_WORD,SOMETHINGTOTRANSLATEWITH,"
done < so.txt
[somedude@dev7 ~]#
这会将您翻译的每一行都回显到标准输出。
希望这可以帮助!
猛击:
#!/bin/bash
while read -ra A; do
printf "%s\t%s" "${A[0]}" "${A[1]}"
printf "\t%s" "$(echo "${A[2]}" | tr '[ABCDEFGHIJKLMNOPQRSTUVQXYZabcdefghijklmnopqrstuvqxyz]' '[ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba]')" "${A[@]:3}"
echo
done
运行为:
bash script.sh < input_file
输出:
Hello how Aiv You
Iam Fine slw about
如果您更改\t
为空格 ( ):
Hello how Ziv You
Iam Fine slw about
另一个版本:
#!/bin/bash
F=({A..Z} {a..z}) R=({Z..A} {z..a})
while read -ra A; do
printf "%s\t%s" "${A[0]}" "${A[1]}"
printf "\t%s" "$(IFS=''; echo "${A[2]}" | tr "[${F[*]}]" "[${R[*]}]")" "${A[@]:3}"
echo
done
这非常笨拙,但可以完成工作(在 bash shell 中)。y
它对整个输入文件使用 sed 的音译运算符。这通过进程替换传递给 awk 和存储在数组中的第三个字段。然后,awk 循环遍历原始文件,并用音译值替换第三个字段的每个实例。
awk -F'\t' -v OFS='\t' 'NR == FNR{a[NR]=$3; next};{$3=a[FNR]; print}' \
<(sed -e 'y/abcdefghijklmnopqrstuvqxyz/zyxwvutsrqponmlkjihgfedcba/' \
-e 'y/ABCDEFGHIJKLMNOPQRSTUVQXYZ/ZYXWVUTSRQPONMLKJIHGFEDCBA/' file) file
像这样的 AWK 脚本
#!/usr/bin/awk -f
BEGIN{
IFS="\t" #input field separator as tab
CHARSET = "abcdefghijklmnopqrstuvwxyz"
}
{
rep_str="" #replacement string
# loop in through each char of third word
for(i=1;i<=length($3);i++){
char = substr($3,i,1)
loc = index(CHARSET,tolower(char))
#check to see if the character is actually an alphabet
if(loc>0){
#get the reverse location of char in the CHARSET
rep_char = substr(CHARSET,27-loc,1)
#change the replacement character to upper case if the original char is uppercase
if(char~/[A-Z]/){
rep_char = toupper(rep_char)
}
}else{
rep_char = char
}
rep_str=rep_str rep_char #final replacement sting formed by concatenation of replaced char rep_char
}
$3 = rep_str
print $0
}
perl -F'\t' -lane '$F[3] =~ tr/ABCDEFGHIJKLMNOPQRSTUVQXYZabcdefghijklmnopqrstuvqxyz/ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba/ ; print "@F"' Filename