Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Evaluation syntax in Unix commands 1

Status
Not open for further replies.

DJR999

Programmer
Nov 19, 2003
16
US
I know this should be simple, but sorry I am fairly new to UNIX and can't find the syntax to make this work.

I have following two commands in a script:

x=`expr $(head -1 filename.ext | cut -c16 | grep [A-Z] | wc -l) + 16`
del=`head -1 filename.ext | cut -c$x`

This works fine as I expect it to. But I want to combine it into one command. Essentially I just want the entire expression that I am assigning to x in the first command to be evaluated at the end of the second command as my argument to the -c attribute of the cut command. But I've tried every way I can to get it to evaluate properly and can't get it.

Thanks for any help.
 
With backquotes that is kind of hard, with [tt]$(cmd)[/tt] construct it is easier and more readable:

[tt]del=$(head -1 filename.ext | cut -c$(expr $(head -1 filename.ext | cut -c16 | grep [A-Z] | wc -l) + 16))[/tt]

But I guess there are easier ways to accomplish the same result.

If an uppercase letter is at position 16 in 1st line, use char at 17th position. I'd probably use [tt]awk[/tt] for that.

HTH,

p5wizard
 
x will return either 16 or 17

17 if the 16'th character of the first line in file filename.ext is uppercase (range of A-Z), otherwise it will return 16


head -1 filename.ext |cut -c16 |grep [A-Z] && {
# 16th character is in range A-Z
head -1 filename.ext |cut -c17
} || {
# 16th character is not in range of A-Z
head -1 filename.ext |cut -c16
}

I used the curly brackets to make it more readable as well as show that you can use several lines of command

Compressed into one line:
head -1 filename.ext |cut -c16 |grep -q [A-Z] && head -1 filename.ext |cut -c17 || head -1 filename.ext |cut -c16
 
I forgot to use -q with grep, in the curly brackets example :)

Explanation:
'grep -q'
- is a quiet grep and will only tell you if it found the expression or not.

Based on the return code from grep I either cut the 17th or the 16th character out from the output of 'head -1 filename.ext'

---- so an appropriate answer to your question could be:
del=`head -1 filename.ext |cut -c16 |grep -q [A-Z] && head -1 filename.ext |cut -c17 || head -1 filename.ext |cut -c16`

/2r
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top