
私のファイルには、dir1.txt
次のディレクトリの名前が含まれています。
2
3
4
ディレクトリ2には、2_1.txtと2_2.txtファイルが含まれています。
ディレクトリ3には3_1.txtファイルと3_2.txtファイルが含まれています。
ディレクトリ4には4_1.txtファイルと4_2.txtファイルが含まれています
。各ファイルには2行が含まれています。
その後、次のようなネストされたループを作成しました。
#!/bin/bash
input="dir1.txt"
while IFS=read -r line
do
for j in "$line/*"
do sed -e '$s/$/\n/' $j
#cat $j; echo
done >> output.txt
done < "$input"
基本的に、リンクされたファイルの間に空白行を置きたいと思います。上記のループを使用すると、dir 2の最後のファイルの内容とdir 3の最初のファイル、およびdir 3の最後のファイルの内容とdir 4の最初のファイルの間に空行のみが表示されます。間に空白行がありますが、同じディレクトリにあるファイルのリンクされた内容の間に空白行を追加したいと思います。私はcat $ j; echo(上記の説明)を使ってみましたが、役に立ちませんでした。入れ子になったforループを使用して再試行しましたが、同じ結果が得られました。私のロジックは間違っていると思います。
答え1
あなたのロジックは正確ですが、機能するにはいくつかの修正が必要でした。
- その後に不足しているスペースが追加されました
IFS
(そうでない場合はエラーが発生しました)。 - 参照を(else)
"$line/*"
に変更します。"$line"/*
sed: can't read 2/*: No such file or directory
- 引用
$j
(より良いスタイルのため)
sed
どちらのバージョンも元々cat/echo
必要な作業を行います。
#!/bin/bash
input="dir1.txt"
while IFS= read -r line
do
for j in "$line"/*
do
sed -e '$s/$/\n/' "$j"
#cat "$j"; echo
done >> output.txt
done < "$input"
答え2
疑わしい場合は、コメントと stderr 出力を使用してください。
また、スクリプトのいくつかの側面がGNU bashバージョン4.2.46(2)リリース(x86_64-redhat-linux-gnu)では機能しません。
#!/bin/bash
input=dir1.txt
# Cycle through input
for dir in $(cat $input)
do
# Prints to stderr
(echo "INFO - Dir: $dir" 1>&2)
# Is dir a directory?
if [ -d $dir ]
then
# Cycle through files
for file in $dir/*
do
# Prints to stderr
(echo "INFO - File: $file" 1>&2)
# Print contents
cat $file
# Blank line.
echo
done
fi
done >> output.txt