Bash 倒转单词,但保持顺序
我有一个有行的文件。我想把单词颠倒过来,但要保持顺序一致。 例如:“测试这个单词” 结果:“tseT siht drow” 我正在使用MAC,所以awk似乎不起作用。 我现在得到了什么Bash 倒转单词,但保持顺序,bash,macos,shell,terminal,Bash,Macos,Shell,Terminal,我有一个有行的文件。我想把单词颠倒过来,但要保持顺序一致。 例如:“测试这个单词” 结果:“tseT siht drow” 我正在使用MAC,所以awk似乎不起作用。 我现在得到了什么 input=FILE_PATH while IFS= read -r line || [[ -n $line ]] do echo $line | rev done < "$input" input=文件路径 而IFS=read-r行| |[[-n$line]] 做 echo$行|修订版 完成
input=FILE_PATH
while IFS= read -r line || [[ -n $line ]]
do
echo $line | rev
done < "$input"
input=文件路径
而IFS=read-r行| |[[-n$line]]
做
echo$行|修订版
完成<“$input”
使用rev和awk
将此视为示例输入文件:
$ cat file
Test this word
Keep the order
尝试:
使用bash
读取时-arr
做
x=“”
对于读取循环中的((i=0;i),您只需迭代字符串中的单词并将它们传递给rev
line="Test this word"
for word in "$line"; do
echo -n " $word" | rev
done
echo # Add final newline
输出
tseT siht drow
$ 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
这里有一个完全避免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"
!/bin/bash
输入=/数据
当读取-r行时;执行
对于$line中的单词;do
输出=`echo$word | rev`
printf“%s”$输出
完成
printf“\n”
完成<“$input”
使用bash,您的状态实际上相当好。您可以使用字符串索引、字符串长度和C-stylefor
循环遍历每个单词中的字符,构建一个反向字符串以进行输出。您可以通过多种方式控制格式以处理单词之间的空格,但一个简单的标志first=1
与e差不多和其他任何东西一样简单。你可以用你的阅读
#!/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
示例使用/输出
tseT siht drow
$ 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
$bash revlines.sh如果xargs在mac上工作:
echo "Test this word" | xargs -n 1 | rev | xargs
这很有效!!添加了| |[-n$line]],所以它也会读取最后一行。@SAllexandriya我刚刚添加了一个示例,演示如何将代码放入脚本并执行脚本。
$ bash revlines.sh <dat/lines2rev.txt
ym god sah saelf
eht tac sah enon
echo "Test this word" | xargs -n 1 | rev | xargs