BASHラインを読む($lineと下のライン出力)

BASHラインを読む($lineと下のライン出力)

この部分を読むのに問題があります。私のファイルにはn行があります。同じループステップで下の行の値をどのように保存できますか?誰かが私を助けることができますか?

ありがとう

詳細:

$ cat testfile.txt
1
2
3
4
5
6
7
8
9
10
while read line; do echo "Current line read: $line"; echo "Line below: `grep -A 1 $line testfile.txt`"; done < testfile.txt
Current line read: 1
Line below: 1
2
--
10
Current line read: 2
Line below: 2
3
Current line read: 3
Line below: 3
4
Current line read: 4
Line below: 4
5
Current line read: 5
Line below: 5
6
Current line read: 6
Line below: 6
7
Current line read: 7
Line below: 7
8
Current line read: 8
Line below: 8
9
Current line read: 9
Line below: 9
10
Current line read: 10
Line below: 10
#

grep -A 1 6 testfile.txt 6 7

grep -A 1 6 testfile.txt | grep -v 6 7

ベストアンサー1

解決策の問題は、grep各行を呼び出すことです。実際、grepは各行を解析します。したがって、n行を含むファイルの場合、その行はn ^ 2回解析され、ロードはgrepかなり高価な呼び出しです。

この例では、次のように単一行バッファを使用しますPrevLine

#!/bin/bash
CurLine=''
isFirstLine=true
while IFS='' read -r LineBelow; do
  if $isFirstLine; then
    echo "This is the first line, so no previous."
  else
    echo "Current line read: ${CurLine}"
    echo "Line below: ${LineBelow}"
  fi
  CurLine="${LineBelow}"
  isFirstLine=false
done <"$1"

実際にtrueto を割り当てるのは文字列の割り当てであり、(if 条件で) 文字列を実行するコマンドとisFirstLine言いました。$isFirstLineとはbashに組み込まれているため、速度に大きな影響を与えずに直接使用できますが、読みやすさが大幅に向上しますtruefalse

最後の行は$1入力ファイル名と呼ばれるので、呼び出しは次のようになります。

./test.sh inputfile.txt

おすすめ記事