[英]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.