简体   繁体   English

在目录中使用awk拆分文件夹名称

[英]splitting folder names with awk in a directory

There are some directories in the working directory with this template 使用此模板的工作目录中有一些目录

cas-2-32
sat-4-64  
...

I want to loop over the directory names and grab the second and third part of folder names. 我想遍历目录名称并获取文件夹名称的第二部分和第三部分。 I have wrote this script. 我已经写了这个脚本。 The body shows what I want to do. 身体显示出我想做的事。 But the awk command seems to be wrong 但是awk命令似乎是错误的

#!/bin/bash
for file in `ls`; do
  if [  -d $file ]; then 
    arg2=`awk -F "-" '{print $2}' $file`
    echo $arg2
    arg3=`awk -F "-" '{print $3}' $file`
    echo $arg3
  fi
done

but it says 但它说

 awk: cmd. line:1: fatal: cannot open file `cas-2-32' for reading (Invalid argument)

awk expects a filename as input. awk需要一个文件名作为输入。 Since you have said the cas-2-32 etc are directories, awk fails for the same reason. 由于您说过cas-2-32等是目录,因此awk失败的原因也相同。

Feed the directory names to awk using echo: 使用echo将目录名称输入awk:

#!/bin/bash
for file in `ls`; do
  if [  -d $file ]; then 
    arg2=$(echo $file | awk -F "-" '{print $2}')
    echo $arg2
    arg3=$(echo $file | awk -F "-" '{print $3}')
    echo $arg3
  fi
done

Simple comand: ls | 简单命令:ls | awk '{ FS="-"; awk'{FS =“-”; print $2" "$3 }' If you want the values in each line just add "\\n" instead of a space in awk's print. print $ 2“” $ 3}'如果希望每行中的值只是在awk的打印结果中添加“ \\ n”而不是空格。

When executed like this 当这样执行时

awk -F "-" '{print $2}' $file

awk treats $file 's value as the file to be parsed, instead of parsing $file 's value itself. awk$file的值视为要解析的文件,而不是解析$file的值本身。

The minimal fix is to use a here-string which can feed the value of a variable into stdin of a command: 最小的解决方法是使用here-string ,该字符串可以将变量的值输入命令的stdin:

awk -F "-" '{print $2}' <<< $file

By the way, you don't need ls if you merely want a list of files in current directory, use * instead, ie 顺便说一句,如果只需要当前目录中的文件列表,则不需要ls ,而是使用*代替,即

for file in *; do

One way: 单程:

#!/bin/bash
for file in *; do
  if [ -d $file ]; then
    tmp="${file#*-}"
    arg2="${tmp%-*}"
    arg3="${tmp#*-}"
    echo "$arg2"
    echo "$arg3"
  fi
done

The other: 另一个:

#!/bin/bash
IFS="-"
for file in *; do
  if [ -d $file ]; then
    set -- $file
    arg2="$2"
    arg3="$3"
    echo "$arg2"
    echo "$arg3"
  fi
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM