LinuxQuestions.org
Welcome to the most active Linux Forum on the web.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-15-2005, 03:26 AM   #1
ringerxyz
LQ Newbie
 
Registered: Nov 2004
Location: China
Distribution: red-flag
Posts: 16

Rep: Reputation: 0
how to manipulate string in script?


for example:
if a string str ="abcde",and now I want get first 4 characters out from the string,
how should I do?
 
Old 02-15-2005, 03:33 AM   #2
jlliagre
Moderator
 
Registered: Feb 2004
Location: Outside Paris
Distribution: Solaris 11.4, Oracle Linux, Mint, Debian/WSL
Posts: 9,789

Rep: Reputation: 492Reputation: 492Reputation: 492Reputation: 492Reputation: 492
bash only way:
Code:
${str:0:4}
portable way:
Code:
expr "$str" : '\(.\{4\}\)'
The latter doesn't output anything if the wariable length is less than 4.

Last edited by jlliagre; 02-15-2005 at 03:34 AM.
 
Old 02-17-2005, 01:14 AM   #3
chrism01
LQ Guru
 
Registered: Aug 2004
Location: Sydney
Distribution: Rocky 9.2
Posts: 18,369

Rep: Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753Reputation: 2753
Another portable method:

echo asdfgh|cut -c1-4
asdf
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Parse String in a Bash script jimwelc Linux - Newbie 8 11-09-2012 07:47 AM
Shell script to find a particular string Prasun1 Linux - General 5 08-30-2005 09:23 AM
script string question MadCactus Programming 4 08-14-2004 04:44 PM
String manipulation with a script. philipina Programming 4 03-16-2004 02:42 PM
String manipulation with a script? philipina General 1 03-15-2004 12:07 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 09:39 AM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration