LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   using sed to grab two characters? (https://www.linuxquestions.org/questions/programming-9/using-sed-to-grab-two-characters-172446/)

nausicaa3000 04-20-2004 07:24 AM

using sed to grab two characters?
 
I am new to sed, but it seems to me this may be able to do what I want. I need to be able to capture two integers from a variable. I have a variable holding a date and time in the form YYYYMMDDHHMMSS.

For example if I have a variable holding 20040419204537, and I want to grab the hour (20) and place it in a new variable.

Also, if possible, I would like to be able to capture the first 8 characters and put them into a new variable (20040419)

Thanks for any help you can give!

itsme86 04-20-2004 08:58 AM

I'm not any good with sed, but here's a couple of C programs to do it easily:

Code:

gethour.c
int main(int argc, char **argv)
{
  if(argc != 2 || strlen(argv[1]) != 14)
    return 1;
  printf("%c%c\n", argv[1][8], argv[1][9]);
  return 0;
}

Code:

getdate.c
int main(int argc, char **argv)
{
  if(argc != 2 || strlen(argv[1]) != 14)
    return 1;
  argv[1][8] = '\0';
  puts(argv[1]);
  return 0;
}


mfeat 04-20-2004 09:33 AM

echo 20040419204537 |
while read a; do
hr=`echo $a | cut -c9-10`
dt=`echo $a | cut -c1-8`
echo $hr $dt
done

jim mcnamara 04-20-2004 09:37 AM

Code:

d="20040419204537"
day=`expr substr $d 9 2 `
echo "date=$d  day=$day"


nausicaa3000 04-20-2004 11:01 AM

Thank you all very much. Such a quick response and good examples. This is a great site!


All times are GMT -5. The time now is 10:54 PM.