【问题标题】:passing parameter from shell script to awk将参数从 shell 脚本传递给 awk
【发布时间】:2013-09-23 18:34:18
【问题描述】:

我想按行数分割我的文本文件

GenTextFile.txt 有 3000 行我想拆分到

GenText_Output_1.txt >> 1000 行(第 1 - 1000 行)

GenText_Output_2.txt>>1000行(1001-2000行)

GenText_Output_3.txt >> 1000行(2001-3000行)

从控制台获取 3 个参数输入,分别是输入名称、输出名称、要拆分的行数

但是当我执行时,它有问题

/devhome/See/Split_file > ./shell_call_awk.sh GenTextFile.txt GenText_Output  1000
awk: syntax error near line 1
awk: bailing out near line 1
awk: can't open in_name

我做错了吗?

-- 这是我的代码--

#!/bin/ksh

#echo "input name : $1"
#echo "output name : $2"
#echo "line split : $3"

input_name=$1
output_name=$2
line_split=$3

awk -v "in_name=$input_name" -v "out_name=$output_name" -v "line=$line_split"
awk 'NR%line==1{x=++i;}{print > out_name"_"x".txt"}' in_name

exit 1;

谢谢。

【问题讨论】:

  • 有什么理由不只是使用split 命令?
  • @Barmar 我使用了 split 命令,文件名的结果是 -> filenameaa,filenameab,filenameac.. 但我希望结果名是 -> filename1, filename2, filename3.. .. 我是 shellscript 的新手,我不知道如何使用 split 命令然后结果如预期。
  • 您看过手册页吗? --numeric-suffixes 选项不符合您的要求吗?
  • 你能展示一个命令的例子吗?我阅读了手册页但没有找到“--numeric-suffixes”选项我找到了这个模式。 split [-linecount | -l linecount] [-a suffixlength] [ file [name]]split [ -b n | nk | nm] [-a suffixlength] [ file [name]]
  • 抱歉,我以为您使用的是 GNU 版本的 split。在大多数 Linux 系统上都可以找到。

标签: linux shell awk


【解决方案1】:

您只需要在一个awk 命令中执行此操作,而不是两个单独的命令。并且输入文件不需要是 awk 变量,它只是一个命令行参数。

awk -v "out_name=$output_name" -v "line=$line_split" 'NR%line==1{x=++i;}{print > (out_name"_"x".txt")}' "$input_name"

您也可以使用split 命令(这需要来自 GNU coreutils 的版本):

split --numeric-suffixes --lines=$line_split "$input_name" "$output_name"_

【讨论】:

  • 感谢您的回复,但仍然出错 /devhome/See/Split_file > ./shell_call_awk.sh file2.txt outputxxx 5 awk: 第 1 行附近的语法错误 awk: 在第 1 行附近退出 如果这种方式不不行,还有别的办法吗?
  • > 后面的文件名表达式需要放在括号中才能使优先级正确。
【解决方案2】:

我尝试跟随,但问题仍然存在。

awk: syntax error near line 1.
awk: bailing out near line 1.

我找到了解决方案here

Solaris is well known for the fact that the some commands under /bin /usr/bin are not POSIX compliant. Instead they have additional compliant versions under /usr/xpg4 and similar hierarchies.

Thus, under Solaris you can use just:

/usr/xpg4/bin/awk -v NAME=MACHINE '$1 == NAME'  /etc/hosts 

Under Solaris 10 this works.

当我使用命令man awk时,我发现我运行的是SunOS 5.9。

然后我用usr/xpg4/bin/awk替换awk

成功了!

@Barmar 非常感谢您对 awk 命令行的建议。

-- 这是我的代码--

input_name=$1
output_name=$2
line_split=$3

/usr/xpg4/bin/awk -v "out_name=$output_name" -v "line=$line_split" 'NR%line==1{x=++i;}{print > out_name""x".txt"}' ${input_name}

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    相关资源
    最近更新 更多