Shell split string stored in array

Source: Internet
Author: User
Tags split

In shell programming, it is often necessary to divide a string separated by a particular delimiter into an array, and in most cases we first think of using awk
However, it is more convenient to actually use the shell's own split array function. If
A= "One,two,three,four"

To split $ A apart, you can:
Old_ifs= "$IFS"
Ifs= ","
Arr= ($a)
ifs= "$OLD _ifs"
For S in ${arr[@]}
Do
echo "$s"
Done

The above code will output
One
Both
Three
Four

Arr= ($a) to split the string $ A into an array $arr ${arr[0]} ${arr[1]} ... Store the segmented array, respectively, 1th 2 ... Item, ${arr[@]} stores the entire array. The variable $ifs stores the delimiter, and here we set it to a comma "," old_ifs is used to back up the default delimiter, which is restored by default when it is finished.



to put a string cut in a file into an array

7481|1|1359475743|1014|1|14.223.145.61:1609
7482|1|1359475752|1014|3|14.223.145.61:1609
7483|1|1359475754|3544|1|121.61.222.187:2971
7484|1|1359475758|11541|3|183.187.51.156:2582

Filename= ' aa.log '   #文件路径
old_ifs= "$IFS"
ifs= "|"
I=0
If [-f ${filename}];then
   while read line
   do
     arr= ( $line)
     echo ${arr[0]}_${arr[1]}_${arr[2]}_${arr[3]}_${arr[4]}_${arr[5]}_${i}
     i=$ ((i+1))
   done < ${filename}
Fi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.