1

Have a string as xxxxxxx.txt

Need to get the only xxxxxxx string without extension.

How to get this using korn shell?

user3761541
  • 157
  • 2
  • 20
  • See http://wiki.bash-hackers.org/syntax/pe and http://mywiki.wooledge.org/BashFAQ/100 -- yes, these are bash resources according to the name, but a majority of bash's extensions to the POSIX sh standard were inspired by ksh. – Charles Duffy Jun 15 '16 at 19:29
  • Related: http://stackoverflow.com/questions/125281/how-do-i-remove-the-file-suffix-and-path-portion-from-a-path-string-in-bash – Charles Duffy Jun 15 '16 at 19:30
  • Also http://stackoverflow.com/questions/12152626/how-can-remove-the-extension-of-a-filename-in-a-shell-script ("shell script", not "bash", so arguably a proper dupe there). – Charles Duffy Jun 15 '16 at 19:32

2 Answers2

1
s=abcdef.txt
s_base=${s%.txt}

...will assign abcdef to s_base.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0
STRING=xxxxxxxxxx.txt
echo $STRING | rev | cut -f 2- -d "." | rev
Tom Solid
  • 2,226
  • 1
  • 13
  • 32
  • This is much, *much* slower than a PE-based approach; requires nonstandard tools; and is also buggy -- look at what happens if your filename is, say `*** hello ***.txt` and the directory you run this in is non-empty (such that `*` matches anything). – Charles Duffy Jun 15 '16 at 19:32
  • Also, there are reasons that all-caps variable names are bad form -- see http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html, paragraph 4, specifying naming conventions for environment variables. (The namespaces overlap, so these conventions necessarily apply to shell variables also). – Charles Duffy Jun 15 '16 at 19:34
  • (Re: "nonstandard tools" -- http://pubs.opengroup.org/onlinepubs/009696699/utilities/contents.html lists POSIX-defined command-line utilities; you'll note that `rev` isn't there). – Charles Duffy Jun 15 '16 at 19:35
  • `STRING="*** hello ***.txt"` will produce `*** hello ***` and `hello.world.txt` will produce `hello.world` because of `-f 2-` – Tom Solid Jun 15 '16 at 19:36
  • 1
    You're missing that the `*`s will be expanded by the shell before `echo` is invoked. Thus, it'll be replaced with a list of filenames in the current working directory. If you wanted to avoid this, you'd need more quotes in your command. Correct as to `hello.world.txt`, though. – Charles Duffy Jun 15 '16 at 19:36
  • That was the reason to try it, before I had posted here... – Tom Solid Jun 15 '16 at 19:39
  • 1
    One of the tricky things about shell is that lots of practices that work well enough with normal/expected inputs will fail badly in unusual cases -- inputs with whitespace or globs, filenames with literal newlines, etc. Thus, testing experimentally is admirable and necessary, but also not a replacement for knowing where the corner cases are and the practices to follow to avoid them. – Charles Duffy Jun 15 '16 at 19:42