英文:
scripting bash for loop awk output in argument
问题
I'm just going to provide the translated code part as requested:
我正在编写一些Bash练习,特别是要检查所有以file-a(数字)命名的文件并将其移动到名为dirA的目录。但是for循环存在一些问题。
我可以在没有for循环的情况下使用以下简单的方式来完成:
mv $(ls -la | awk '$9 ~ /-a[0-9]+/ {print $9}') dirA
但我想使用for循环来完成,但我无法做到。以下是脚本:
FILES=$(ls -la | awk '$9 ~ /-a[0-9]+/ {print $9}')
for arg in "$FILES"
do
mv $arg dirA
done
Please note that I've made some corrections to the code to address the issues in the original script.
英文:
im writing some bash exercises, this in particular wants to check all the files named file-a(sonenumber) and move it to directory named dirA
But there's some problem with for loop
i can do that without for loop just simply writing
mv $(ls -la | awk '$9 - /-a[0-9]+/ {print $9}') dirA
but i wanna do it with a for and i cant do that
there's the script
FILES=(ls -la | awk '$9 - /-a[0-9]+/ {print $9}')
for arg in "$FILES"
do
mv $arg dirA
done
答案1
得分: 3
不需要使用循环,只需使用 shell glob
:
mv -- *-a[0-9]* dirA
如果坚持要使用循环:
files=( *-a[0-9]* )
for f in "${files[@]}"; do
mv "$f" dirA/
done
或者
for f in *-a[0-9]*; do
mv "$f" dirA/
done
但请避免解析 ls
输出。
ls
是一个用于交互式查看目录元数据的工具。任何尝试使用代码解析 ls
输出的尝试都是错误的。使用通配符更简单且正确:for file in *.txt
。阅读 http://mywiki.wooledge.org/ParsingLs
不要使用大写变量名,参考 Don't use UPPER case variables。
英文:
No need a for loop, just a shell glob
:
mv -- *-a[0-9]* dirA
If you insist for a loop:
files=( *-a[0-9]* )
for f in "${files[@]}"; do
mv "$f" dirA/
done
or
for f in *-a[0-9]*; do
mv "$f" dirA/
done
But please, avoid parsing ls
output.
ls
is a tool for interactively looking at directory metadata. Any attempts at parsing ls
output with code are broken. Globs are much more simple AND correct: for file in *.txt
. Read http://mywiki.wooledge.org/ParsingLs
答案2
得分: 1
You're not setting FILES
to the output of the command. For that, you need to use $(command)
. To make it an array, wrap another set of ()
around that.
然后,要循环遍历数组内容,请使用 "${FILES[@]}"
。
I'm not sure why you're using ls -la
when you could just use ls -a
. Then each filename will be a single line, you don't have to extract $9
.
然而,最好不要解析ls
的输出。
英文:
You're not setting FILES
to the output of the command. For that, you need to use $(command)
. To make it an array, wrap another set of ()
around that.
Then to loop over the array contents, use "${FILES[@]}
.
I'm not sure why you're using ls -la
when you could just use ls -a
. Then each filename will be a single line, you don't have to extract $9
.
FILES=($(ls -a | awk '/-a[0-9]+/'))
for arg in "${FILES[@]}"
do
mv "$arg" dirA
done
However, it's best not to parse the output of ls
.
答案3
得分: -6
我修改了你的代码以在for循环中运行。
FILES=$(ls -la | awk '/-a[0-9]+/ {print $9}')
for arg in $FILES
do
mv $arg dirA
done
英文:
I modified your code to work in the for loop.
FILES=$(ls -la | awk '/-a[0-9]+/ {print $9}')
for arg in $FILES
do
mv $arg dirA
done
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论