[英]Reverse the words but keep the order Bash
我有一个带线的文件。 我想颠倒这两个词,但要使其顺序保持一致。 例如:“测试此词”结果:“ tseT siht drow”
我正在使用MAC,因此awk似乎不起作用。 我现在得到的
input=FILE_PATH
while IFS= read -r line || [[ -n $line ]]
do
echo $line | rev
done < "$input"
这是一个完全避免awk的解决方案
#!/bin/bash
input=./data
while read -r line ; do
for word in $line ; do
output=`echo $word | rev`
printf "%s " $output
done
printf "\n"
done < "$input"
如果xargs在Mac上可以使用:
echo "Test this word" | xargs -n 1 | rev | xargs
将此视为示例输入文件:
$ cat file
Test this word
Keep the order
尝试:
$ rev <file | awk '{for (i=NF; i>=2; i--) printf "%s%s",$i,OFS; print $1}'
tseT siht drow
peeK eht redro
(这使用awk,但是,由于它不使用高级awk功能,因此应该可以在MacOS上使用。)
在脚本中使用
如果您需要将以上内容放入脚本中,请创建一个类似以下的文件:
$ cat script
#!/bin/bash
input="/Users/Anastasiia/Desktop/Tasks/test.txt"
rev <"$input" | awk '{for (i=NF; i>=2; i--) printf "%s%s",$i,OFS; print $1}'
然后,运行文件:
$ bash script
tseT siht drow
peeK eht redro
while read -a arr
do
x=" "
for ((i=0; i<${#arr}; i++))
do
((i == ${#arr}-1)) && x=$'\n'
printf "%s%s" $(rev <<<"${arr[i]}") "$x"
done
done <file
将以上内容应用于我们的相同测试文件:
$ while read -a arr; do x=" "; for ((i=0; i<${#arr}; i++)); do ((i == ${#arr}-1)) && x=$'\n'; printf "%s%s" $(rev <<<"${arr[i]}") "$x"; done; done <file
tseT siht drow
peeK eht redro
在读取循环中,您可以遍历字符串中的单词并将其传递给rev
line="Test this word"
for word in "$line"; do
echo -n " $word" | rev
done
echo # Add final newline
产量
tseT siht drow
bash实际上让您状态良好。 您可以使用字符串索引 , 字符串长度和C样式for
循环,以循环遍历每个单词中的字符,从而构建要输出的反向字符串。 您可以通过多种方式控制格式来处理单词之间的空格,但是简单的标记first=1
几乎和其他任何操作一样简单。 您可以阅读以下内容,
#!/bin/bash
while read -r line || [[ -n $line ]]; do ## read line
first=1 ## flag to control space
a=( $( echo $line ) ) ## put line in array
for i in "${a[@]}"; do ## for each word
tmp= ## clear temp
len=${#i} ## get length
for ((j = 0; j < len; j++)); do ## loop length times
tmp="${tmp}${i:$((len-j-1)):1}" ## add char len - j to tmp
done
if [ "$first" -eq '1' ]; then ## if first word
printf "$tmp"; first=0; ## output w/o space
else
printf " $tmp" ## output w/space
fi
done
echo "" ## output newline
done
输入示例
$ cat dat/lines2rev.txt
my dog has fleas
the cat has none
使用/输出示例
$ bash revlines.sh <dat/lines2rev.txt
ym god sah saelf
eht tac sah enon
仔细检查一下,如果您有任何问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.