can anyone tell me how I can print the first or the last character from a sh file ?

i have done research on regular expression and the grep... i couldn't find any cmd that i can use to achieve this task. Thanks a lot.

I don't know of any command that will do this directly for you - and awk would probably be the way to go, but I'm no awk guru. This could probably also be done through some very impressive sed magic - but again, I'm no sed guru.

So doing this with a shell script, I would say the first logical step would be to get the first line, and the last line - from there we can manipulate those two strings.

FILE=$1   #read the filename as an argument
FIRST_LINE=`head -1 $FILE` 
LAST_LINE=`tail -1 $FILE`

The next easy part will be grabbing the first letter, using cut:

FIRST_CHAR=`echo $FIRST_LINE | cut -c 1`

Of course, we could have skipped assigning the FIRST_LINE variable with this:

FIRST_CHAR=`head -1 $FILE | cut -c 1`

Getting the last character is a little more dificult.

num_chars=`echo $LAST_LINE | wc -c` # number of characters in the last line
num_chars=`expr  $num_chars - 1`    #subtract 1 because counting starts at 1, not 0
LAST_CHAR=`echo $LAST_LINE | cut -c $num_chars`

All in all, we end up with:

FILE=$1   #read the filename as an argument
FIRST_CHAR=`head -1 $FILE | cut -c 1`
LAST_LINE=`tail -1 $FILE`

num_chars=`echo $LAST_LINE | wc -c` # number of characters in the last line
num_chars=`expr  $num_chars - 1`    #subtract 1 because counting starts at 1, not 0

LAST_CHAR=`echo $LAST_LINE | cut -c $num_chars`

echo "${FIRST_CHAR}${LAST_CHAR}"

#echo "${FIRST_CHAR} ${LAST_CHAR}"   #put a space between
#echo "${FIRST_CHAR}\n${LAST_CHAR}"  #return on different lines

voila.

can anyone tell me how I can print the first or the last character from a sh file ?

i have done research on regular expression and the grep... i couldn't find any cmd that i can use to achieve this task. Thanks a lot.

awk 'BEGIN{FS=""}NR==1{print $1}{l=$NF}END{print l}' file
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.