3

1.my shell file is

 [root@node3 script]# cat hi.sh
 #!/bin/bash
 strings="sdsf sdsda sdsadx"
 echo `awk "{print substr($0,0,9)}"<<<$strings`

2.exe my shell file

[root@node3 script]# sh hi.sh 

awk: {print substr(hi.sh,0,9)}

awk:                 ^ syntax error

awk: 致命错误: 0 是 substr 的无效参数个数

so how to use the awk's $0 in shell file ?

the $0 default file's name .

another ques. i want use the var $0 about awk but the another $variable in the shell file.what should i do ?

$ cat hi.sh 
#!/bin/bash 
strings="sdsf sdsda sdsadx" 
num=9 
echo \`awk '{print substr($0,0,$num)}' <<< $strings\`
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
here
  • 75
  • 1
  • 12

1 Answers1

2

The problem with your script is use of double quotes in awk. Replace them with single quotes.

When you use double quotes, the $0 inside it is treated as first argument to the script, which in this case is script name hi.sh. If you use single quotes, you can use $0 as awk argument to display whole row.

Also echo is not needed here, you can just use awk '{print substr($0,0,9)}' <<< $strings

$ cat hi.sh
#!/bin/bash
strings="sdsf sdsda sdsadx"
#echo `awk '{print substr($0,0,9)}' <<< $strings` --echo not needed
awk '{print substr($0,0,9)}' <<< $strings
$
$ sh hi.sh
sdsf sdsd
Utsav
  • 7,914
  • 2
  • 17
  • 38
  • 1
    i replaced and it worked. thanks u. ps: your code on the web still show double quotes . – here Jun 22 '17 at 08:23
  • Good catch, fixed. – Utsav Jun 22 '17 at 08:25
  • Yes, mentioned that in the answer as well. I just wanted to point the error in OP's query, hence kept the rest of the code as it is. – Utsav Jun 22 '17 at 08:33
  • in `awk` there is an option to define variable outside like `awk var=$num ....` then use can use `$var` inside awk. Not exactly sure on the command so better to do a google search :) – Utsav Jun 22 '17 at 08:38
  • i kown what u say .use the awk's variable to solve it . – here Jun 22 '17 at 08:42