0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ls の実行結果を for 文で処理するワンライナー

Last updated at Posted at 2020-09-24

やりたいこと

1階層上に複数あるディレクトリの中にあるファイルを今いるディレクトリに全てコピーすること。

つまり、これを↓

Before
$ tree -c
.
├── a
│   └── a.text
├── b
│   └── b.text
└── c
    └── c.text

こうしたい↓

After
$ tree -c
.
├── a
│   └── a.text
├── b
│   └── b.text
├── c
│   └── c.text
├── a.text
├── b.text
└── c.text

そのときに『 ls の実行結果を for 文で処理するワンライナーがあればうまく行くのに、、、』と思ったので、それを試してみた備忘録になります。

ls の実行結果を for 文で処理する方法

複数行の場合

複数行(一般化)
$ for a in $(ls .); do
   実行させたい処理
done
複数行(サンプル)
$ for a in $(ls .); do
   echo $a
done

(実行結果)
a
b
c

ワンライナーの場合

ワンライナー(一般化)
$ for a in $(ls .); 実行させたい処理 $a; done
ワンライナー(サンプル)
$ for a in $(ls .); do echo $a; done

(実行結果)
a
b
c

echo $a;; を忘れずに。

ワンライナーで for 文を2週することも可能

ワンライナーでfor文を2週
for a in $(ls .); do for b in $(ls $a); do echo "$a/$b"; done; done

(実行結果)
a/a.text
b/b.text
c/c.text

やりたいことをやってみる

やりたいこと:1階層上に複数あるディレクトリの中にあるファイルを今いるディレクトリに全てコピーする

失敗例

$ for a in $(ls .); do cp -p "$a/*" . ; done

(実行結果)
cp: a/*: No such file or directory
cp: a.text/*: Not a directory
cp: b/*: No such file or directory
cp: b.text/*: Not a directory
cp: c/*: No such file or directory
cp: c.text/*: Not a directory

なんか怒られた、、、
こういう書き方だと*(ワイルドカード)が展開されないみたいですね。。。

成功例

ワイルドカードを使わずに素直に2周させてみました。

$ for a in $(ls .); do for b in $(ls $a); do cp -p "$a/$b" .; done; done

$ tree -c
.
├── a
│   └── a.text
├── b
│   └── b.text
├── c
│   └── c.text
├── a.text
├── b.text
└── c.text

いけた!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?