在來自標準輸入的傳入字串流中,交換偶數行和奇數行。我試過這樣做,但是從檔案中讀取并且$i -lt $a.count不作業:
$a= gc test.txt
for($i=0;$i -lt $a.count;$i )
{
if($i%2)
{
$a[$i-1]
}
else
{
$a[$i 1]
}
}
請幫我解決這個問題
uj5u.com熱心網友回復:
一個純粹的重擊讀取stdin和寫入的解決方案stdout:
#!/bin/bash
while read -r odd && read -r even
do
echo "$even"
echo "$odd"
unset odd
done
# in case there are an odd number of lines in the file, print the last "odd" line read
if [[ -n $odd ]]; then
echo "$odd"
fi
從一個檔案讀取并寫入另一個檔案:
#!/bin/bash
infile="inputfile"
outfile="outputfile"
{
while read -r odd && read -r even
do
echo "$even"
echo "$odd"
unset odd
done < "$infile"
# in case there are an odd number of lines in the file, print the last "odd" line read
if [[ -n $odd ]]; then
echo "$odd"
fi
} > "$outfile"
如果要覆寫infile,請以:
mv "$outfile" "$infile"
uj5u.com熱心網友回復:
建議一行awk腳本:
awk '!(NR%2){print$0;print r}NR%2{r=$0}' input.txt
awk腳本解釋
!(NR % 2){ # if row number divide by 2 witout reminder
print $0; # print current row
print evenRow; # print saved row
}
(NR % 2){ # if row number divided by 2 with reminder
evenRow = $0; # save current row in variable
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435678.html
